<template>
	<view class="order-page">
		<view class="order-form-container">
			<view class="order-form">
				<!-- 产品编号 -->
				<view class="form-item">
					<view>产品ID：</view>
					<view>{{ product.id || '无' }}</view>
				</view>

				<!-- 产品名称 -->
				<view class="form-item">
					<view>产品名称：</view>
					<uni-easyinput v-model="product.name" placeholder="请输入产品名称" />
				</view>

				<!-- 产品编码 -->
				<view class="form-item">
					<view>产品编码：</view>
					<uni-easyinput v-model="product.no" placeholder="请输入产品编码" />
				</view>

				<!-- 单位 -->
				<view class="form-item">
					<view>单位：</view>
					<picker mode="selector" :range="unitNames" @change="onUnitChange" :value="unitIndex">
						<view class="picker">{{ unitNames[unitIndex] || '请选择单位' }}</view>
					</picker>
				</view>

				<!-- 产品状态 -->
				<view class="form-item">
					<view>产品状态：</view>
					<uni-easyinput v-model="product.status" placeholder="请输入产品状态" />
				</view>

				<!-- 产品分类 -->
				<view class="form-item">
					<view>产品分类：</view>
					<picker mode="selector" :range="categoryNames" @change="onCategoryChange" :value="categoryIndex">
						<view class="picker">{{ categoryNames[categoryIndex] || '请选择产品分类' }}</view>
					</picker>
				</view>

				<!-- 负责人的用户编号 -->
				<view class="form-item">
					<view>负责人：</view>
					<uni-easyinput v-model="product.ownerUserId" placeholder="请输入负责人的用户编号" />
				</view>

				<!-- 产品规格 -->
				<view class="form-item">
					<view>产品规格：</view>
					<uni-easyinput v-model="product.standard" placeholder="请输入产品规格" />
				</view>

				<!-- 价格 -->
				<view class="form-item">
					<view>价格：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="product.price" placeholder="请输入价格" />
					</view>
				</view>
				<!-- 采购价格，单位：元 -->
				<view class="form-item">
					<view>采购价格：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="product.purchasePrice"
							placeholder="请输入采购价格" />
					</view>
				</view>

				<!-- 销售价格，单位：元 -->
				<view class="form-item">
					<view>销售价格：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="product.salePrice"
							placeholder="请输入销售价格" />
					</view>
				</view>

				<!-- 最低价格，单位：元 -->
				<view class="form-item">
					<view>最低价格：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="product.minPrice" placeholder="请输入最低价格" />
					</view>
				</view>

				<!-- 保质期天数 -->
				<view class="form-item">
					<view>保质期天：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="product.expiryDay"
							placeholder="请输入保质期天数" />
					</view>
				</view>
				<!-- 基础重量（kg） -->
				<view class="form-item">
					<view>基础重量：</view>
					<view class="picker">
						<input class="uni-input" type="digit" v-model.number="product.weight" placeholder="请输入基础重量" />
					</view>
				</view>
				<!-- 产品描述 -->
				<view class="form-item">
					<view>产品描述：</view>
					<uni-easyinput type="textarea" v-model="product.description" placeholder="请输入产品描述" />
				</view>
				<!-- 提交按钮 -->
				<view class="form-item">
					<button type="button" @click="submitForm">{{ isEdit ? '修改' : '新增' }}</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getProduct,
		createProduct,
		updateProduct,
		getCategory,
		getProductUnit
	} from "@/sheep/api/erp/product.js";
 import DictApi from "@/sheep/api/system/dict.js";

	export default {
		data() {
			return {
				productId: "", // 从路由参数获取产品ID
				product: {
					id: null,
					name: '',
					no: '',
					categoryId: null,
					unit: null,
					status: null, // 默认状态为 null，确保必填项验证生效
					standard: '',
					description: '',
					expiryDay: null,
					weight: null,
					purchasePrice: null,
					salePrice: null,
					minPrice: null,
					ownerUserId: null, // 新增字段
					remark: '',
					price: null, // 新增字段，对应后端的 "价格"
					createTime: null,
				}, // 用于存储产品详情
				isEdit: false, // 是否为编辑模式
				categoryIds: [], // 产品分类列表
				unitIds: [], // 单位列表
				categoryNames: [], // 分类名称列表
				unitNames: [], // 单位名称列表
				categoryIndex: -1, // 选择的分类索引
				unitIndex: -1, // 选择的单位索引
			};
		},

		methods: {
			setPageTitle() {
			      const title = this.isEdit ? "修改产品" : "新增产品";
			      uni.setNavigationBarTitle({
			        title,
			      });
			    },
			async fetchProductUnit() {
				try {
					const res = await DictApi.getDictLists("crm_product_unit");
					this.unitIds = res.data; // 获取单位数据
					this.unitNames = res.data.map(item => item.label); // 提取单位名称
					if (this.isEdit) {
						this.unitIndex = this.unitIds.findIndex(item => item.value == this.product.unit);
					}
				} catch (error) {
					uni.showToast({
						title: "获取产品单位失败:" + error.msg,
						icon: "none"
					});
				}
			},
			async fetchProductDetails() {
				if (!this.productId) return; // 如果没有 productId，表示是新增，不需要请求数据
				await getProduct(this.productId).then((res) => {
						this.product = res.data;
						this.isEdit = true;
						this.categoryIndex = this.categoryIds.findIndex(item => item.id === this.product
							.categoryId);
						this.unitIndex = this.unitIds.findIndex(item => item.value == this.product.unit);
					})
					.catch(() => {
						uni.showToast({
							title: "获取产品详情失败",
							icon: "none"
						});
					});
			},
			async fetchCategory() {
				try {
					const res = await getCategory();
					this.categoryIds = res.data; // 获取分类数据
					this.categoryNames = res.data.map(item => item.name); // 提取分类名称
					if (this.isEdit) {
						this.categoryIndex = this.categoryIds.findIndex(item => item.id === this.product.categoryId);
					}
				} catch (error) {
					uni.showToast({
						title: "获取产品分类失败",
						icon: "none"
					});
				}
			},
			onCategoryChange(e) {
				this.categoryIndex = e.detail.value;
				if (this.categoryIndex !== -1) {
					this.product.categoryId = this.categoryIds[this.categoryIndex].id;
				}
			},
			onUnitChange(e) {
				this.unitIndex = e.detail.value;
				if (this.unitIndex !== -1) {
					this.product.unit = this.unitIds[this.unitIndex].value;
				}
			},
			submitForm() {
				if (this.isEdit) {
					// 修改请求
					this.updateProduct();
				} else {
					// 新增请求
					this.createProduct();
				}
			},
			createProduct() {
				createProduct(this.product)
					.then(() => {
						uni.showToast({
							title: "新增成功",
							icon: "success"
						});
						uni.navigateBack(); // 新增后返回
					})
					.catch((err) => {
						uni.showToast({
							title: err.msg || "新增失败",
							icon: "none"
						});
					});
			},
			updateProduct() {
				updateProduct(this.product)
					.then(() => {
						uni.showToast({
							title: "修改成功",
							icon: "success"
						});
						uni.navigateBack(); // 修改后返回
					})
					.catch((err) => {
						uni.showToast({
							title: err.message || "修改失败",
							icon: "none"
						});
					});
			},
		},

		onLoad() {
			  // 从路由参数或存储中获取 productId
			this.productId = uni.getStorageSync('productId') || ''; 
			this.isEdit = !!this.productId; // 如果有 productId，则为编辑模式
			this.setPageTitle(); // 设置页面标题
			this.fetchProductUnit();
			this.fetchCategory();
			this.fetchProductDetails();
		},
	};
</script>
 